<template>
  <div class="min-h-screen bg-gray-50">
    <div class="main-container">
      <!-- 筛选和搜索区域 -->
      <div class="filter-section">
        <!-- ... 这部分无需修改 ... -->
        <div class="filter-grid">
          <!-- 搜索框 -->
          <div class="search-container">
            <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <circle cx="11" cy="11" r="8"/>
              <path d="m21 21-4.35-4.35"/>
            </svg>
            <input
              type="text"
              placeholder="搜索管理员、模块或操作名称..."
              class="search-input"
              v-model="searchTerm"
            />
          </div>

          <!-- 操作类型筛选 -->
          <div class="select-container">
            <svg class="select-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <polygon points="22,3 2,3 10,12.46 10,19 14,21 14,12.46 22,3"/>
            </svg>
            <select class="filter-select" v-model="filterAction">
              <option value="all">所有操作类型</option>
              <option value="新建分组">新建分组</option>
              <option value="删除分组">删除分组</option>
              <option value="发送普通消息">发送普通消息</option>
              <option value="发送模板消息">发送模板消息</option>
              <option value="删除消息">删除消息</option>
            </select>
          </div>

          <!-- 导出按钮 -->
          <button @click="exportLogs" class="export-btn">
            <svg class="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
              <polyline points="7,10 12,15 17,10"/>
              <line x1="12" y1="15" x2="12" y2="3"/>
            </svg>
            导出日志
          </button>
        </div>

        <!-- 日期范围选择 -->
        <div class="date-filter">
          <svg class="calendar-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
            <line x1="16" y1="2" x2="16" y2="6"/>
            <line x1="8" y1="2" x2="8" y2="6"/>
            <line x1="3" y1="10" x2="21" y2="10"/>
          </svg>
          <span class="date-label">时间范围：</span>
          <input
            type="date"
            class="date-input"
            v-model="dateRange.start"
          />
          <span class="date-separator">至</span>
          <input
            type="date"
            class="date-input"
            v-model="dateRange.end"
          />
          <button
            v-if="dateRange.start || dateRange.end"
            @click="clearDateRange"
            class="clear-btn"
          >
            清除
          </button>
        </div>
      </div>

      <!-- 加载和错误提示 -->
      <div v-if="loading" class="status-message">正在加载日志数据...</div>
      <div v-if="error" class="status-message error-message">加载失败：{{ error }}</div>

      <!-- 主内容区域 (加载完成且无错误时显示) -->
      <div v-if="!loading && !error">
        <!-- 统计信息 -->
        <div class="stats-grid">
           <!-- ... 这部分无需修改 ... -->
          <div class="stat-card">
            <div class="stat-content">
              <div class="stat-info">
                <p class="stat-label">总记录数</p>
                <p class="stat-value">{{ filteredLogs.length }}</p>
              </div>
              <div class="stat-icon stat-icon-blue">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                  <polyline points="22,12 18,12 15,21 9,3 6,12 2,12"/>
                </svg>
              </div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-content">
              <div class="stat-info">
                <p class="stat-label">分组管理操作</p>
                <p class="stat-value stat-value-green">{{ getModuleOperationCount('分组管理') }}</p>
              </div>
              <div class="stat-icon stat-icon-green">
                <div class="stat-dot"></div>
              </div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-content">
              <div class="stat-info">
                <p class="stat-label">消息发送中心</p>
                <p class="stat-value stat-value-blue">{{ getModuleOperationCount('消息发送中心') }}</p>
              </div>
              <div class="stat-icon stat-icon-blue">
                <div class="stat-dot"></div>
              </div>
            </div>
          </div>
          <!-- === “事务管理操作”卡片已删除 === -->
        </div>

        <!-- 日志列表 -->
        <div class="table-container">
          <div class="table-wrapper">
            <table class="log-table">
              <thead class="table-header">
                <tr>
                  <th class="table-th">操作时间</th>
                  <th class="table-th">管理员</th>
                  <th class="table-th">模块</th>
                  <th class="table-th">操作类型</th>
                  <th class="table-th">操作名称</th>
                  <th class="table-th">状态</th>
                </tr>
              </thead>
              <!-- 添加 v-if 来处理无数据的情况 -->
              <tbody v-if="currentLogs.length > 0" class="table-body">
                <!-- === 修改点：所有 log.snake_case 改为 log.camelCase === -->
                <tr v-for="log in currentLogs" :key="log.logId" class="table-row">
                  <td class="table-td">{{ formatDateTime(log.operationTime) }}</td>
                  <td class="table-td">
                    <div class="user-name">{{ log.userName }}</div>
                  </td>
                  <td class="table-td">{{ log.module }}</td>
                  <td class="table-td">
                    <span :class="getActionBadgeClass(log.actionType)">
                      {{ log.actionType }}
                    </span>
                  </td>
                  <td class="table-td">
                    <div class="target-text">{{ log.actionName }}</div>
                  </td>
                  <td class="table-td">
                    <div class="status-container">
                      <div :class="getStatusIconClass(log.status)"></div>
                      <span :class="getStatusTextClass(log.status)">
                        {{ log.status }}
                      </span>
                    </div>
                  </td>
                </tr>
              </tbody>
              <tbody v-else>
                <tr>
                  <td colspan="6" class="no-data-message">
                    没有找到符合条件的日志记录。
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 分页 -->
          <div v-if="filteredLogs.length > 0" class="pagination-container">
            <!-- ... 这部分无需修改 ... -->
            <div class="pagination-mobile">
              <button
                @click="prevPage"
                :disabled="currentPage === 1"
                class="pagination-btn"
              >
                上一页
              </button>
              <button
                @click="nextPage"
                :disabled="currentPage === totalPages"
                class="pagination-btn"
              >
                下一页
              </button>
            </div>
            <div class="pagination-desktop">
              <div class="pagination-info">
                <p class="pagination-text">
                  显示第 <span class="font-medium">{{ indexOfFirstLog + 1 }}</span> 到
                  <span class="font-medium">{{ Math.min(indexOfLastLog, filteredLogs.length) }}</span> 条，
                  共 <span class="font-medium">{{ filteredLogs.length }}</span> 条记录
                </p>
              </div>
              <div class="pagination-nav">
                <button
                  @click="prevPage"
                  :disabled="currentPage === 1"
                  class="pagination-btn-desktop pagination-btn-left"
                >
                  上一页
                </button>
                <button
                  v-for="page in visiblePages"
                  :key="page"
                  @click="setCurrentPage(page)"
                  :class="getPageBtnClass(page)"
                >
                  {{ page }}
                </button>
                <button
                  @click="nextPage"
                  :disabled="currentPage === totalPages"
                  class="pagination-btn-desktop pagination-btn-right"
                >
                  下一页
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// === 1. 导入API ===
import { getLogs } from '@/api/log.js';

export default {
  name: 'ArchiveLogPage',
  data() {
    return {
      logs: [],
      filteredLogs: [],
      searchTerm: '',
      filterAction: 'all',
      dateRange: { start: '', end: '' },
      currentPage: 1,
      logsPerPage: 10,
      // === 2. 添加加载和错误状态 ===
      loading: true,
      error: null
    }
  },
  computed: {
    // ... computed部分无需修改
    indexOfLastLog() {
      return this.currentPage * this.logsPerPage;
    },
    indexOfFirstLog() {
      return this.indexOfLastLog - this.logsPerPage;
    },
    currentLogs() {
      return this.filteredLogs.slice(this.indexOfFirstLog, this.indexOfLastLog);
    },
    totalPages() {
      return Math.ceil(this.filteredLogs.length / this.logsPerPage);
    },
    visiblePages() {
      const pages = [];
      const maxVisible = 5;
      const start = Math.max(1, this.currentPage - Math.floor(maxVisible / 2));
      const end = Math.min(this.totalPages, start + maxVisible - 1);

      for (let i = start; i <= end; i++) {
        pages.push(i);
      }
      return pages;
    }
  },
  watch: {
    // ... watch部分无需修改
    searchTerm() { this.filterLogs(); },
    filterAction() { this.filterLogs(); },
    dateRange: {
      handler() { this.filterLogs(); },
      deep: true
    }
  },
  mounted() {
    // 方法名不变，但内部实现已改变
    this.initializeLogs();
  },
  methods: {
    // === 3. 修改 initializeLogs 方法以调用API ===
    async initializeLogs() {
      this.loading = true;
      this.error = null;
      try {
        const responseData = await getLogs();

        // --- 在这里添加调试代码 ---
        console.log("从API获取到的原始响应:", responseData);
        // -------------------------

        // 假设你的axios封装会把数据放在 .data 属性里
        const logsArray = responseData.data;

        // --- 添加一个健壮性检查 ---
        if (!Array.isArray(logsArray)) {
          // 如果 logsArray 依然不是一个数组，就抛出错误，防止程序继续执行
          console.error("响应数据中的 'data' 属性不是一个数组!", logsArray);
          throw new Error("从服务器返回的数据格式不正确。");
        }
        // -------------------------

        // 现在对真正的数组进行排序
        this.logs = logsArray.sort((a, b) => new Date(b.operationTime) - new Date(a.operationTime));
        this.filteredLogs = [...this.logs];

      } catch (err) {
        console.error("获取日志失败:", err);
        this.error = err.message || '无法连接到服务器';
      } finally {
        this.loading = false;
      }
    },

    // === 4. 修改 filterLogs, exportLogs, 和其他方法以适配 camelCase 数据 ===
    filterLogs() {
      let filtered = this.logs;

      // 搜索功能
      if (this.searchTerm) {
        const lowerCaseSearch = this.searchTerm.toLowerCase();
        filtered = filtered.filter(log =>
          (log.userName && log.userName.toLowerCase().includes(lowerCaseSearch)) ||
          (log.module && log.module.toLowerCase().includes(lowerCaseSearch)) ||
          (log.actionType && log.actionType.toLowerCase().includes(lowerCaseSearch)) ||
          (log.actionName && log.actionName.toLowerCase().includes(lowerCaseSearch))
        );
      }

      // 操作类型筛选
      if (this.filterAction !== 'all') {
        filtered = filtered.filter(log => log.actionType === this.filterAction);
      }

      // 日期范围筛选
      if (this.dateRange.start && this.dateRange.end) {
        const startDate = new Date(this.dateRange.start);
        // 将结束日期设为当天的最后一刻，以包含当天所有记录
        const endDate = new Date(this.dateRange.end);
        endDate.setHours(23, 59, 59, 999);

        filtered = filtered.filter(log => {
          const logDate = new Date(log.operationTime);
          return logDate >= startDate && logDate <= endDate;
        });
      }

      this.filteredLogs = filtered;
      this.currentPage = 1; // 每次筛选后重置到第一页
    },

    exportLogs() {
      const csvHeader = "操作时间,管理员,模块,操作类型,操作名称,状态\n";
      const csvRows = this.filteredLogs.map(log =>
        [
          this.formatDateTime(log.operationTime), // 使用格式化后的时间
          log.userName,
          log.module,
          log.actionType,
          `"${log.actionName.replace(/"/g, '""')}"`, // 处理内容中的双引号
          log.status
        ].join(",")
      ).join("\n");

      const csvString = '\uFEFF' + csvHeader + csvRows; // 添加BOM头防止Excel打开乱码

      const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement("a");
      const url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", `系统日志_${new Date().toISOString().split('T')[0]}.csv`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    formatDateTime(dateTimeString) {
      if (!dateTimeString) return 'N/A';
      const date = new Date(dateTimeString);
      return date.toLocaleString('zh-CN', { hour12: false });
    },

    // ... 其他辅助方法，大部分无需修改，只需确认字段名 ...
    getModuleOperationCount(moduleName) {
      return this.filteredLogs.filter(log => log.module === moduleName).length;
    },
    // 一个更具体的样式分配示例
    getActionBadgeClass(actionType) {
      if (!actionType) return 'operation-badge-default';
      if (actionType.includes('删除')) {
        return 'operation-badge operation-badge-delete'; // 红色
      }
      if (actionType.includes('新建') || actionType.includes('发送普通消息')) {
        return 'operation-badge operation-badge-create'; // 蓝绿色
      }
      if (actionType.includes('发送模板消息')) {
        return 'operation-badge operation-badge-template'; // 你需要自己定义这个新样式
      }
      return 'operation-badge operation-badge-default'; // 灰色
    },
    getStatusIconClass(status) { return status === '成功' ? 'status-icon status-icon-success' : 'status-icon status-icon-failed'; },
    getStatusTextClass(status) { return status === '成功' ? 'status-text status-text-success' : 'status-text status-text-failed'; },
    getPageBtnClass(page) { return this.currentPage === page ? 'pagination-btn-desktop pagination-btn-active' : 'pagination-btn-desktop pagination-btn-normal'; },
    clearDateRange() { this.dateRange = { start: '', end: '' }; },
    prevPage() { if (this.currentPage > 1) this.currentPage--; },
    nextPage() { if (this.currentPage < this.totalPages) this.currentPage++; },
    setCurrentPage(page) { this.currentPage = page; }
  }
}
</script>
<style scoped>


/* 新增一些样式 */
.status-message {
  text-align: center;
  padding: 40px;
  font-size: 1.2rem;
  color: #666;
}
.error-message {
  color: #d9534f;
}
.no-data-message {
  text-align: center;
  padding: 40px;
  color: #999;
}
* {
  box-sizing: border-box;
}

.min-h-screen {
  min-height: 100vh;
}

.bg-gray-50 {
  background-color: #f9fafb;
}
.operation-badge-template {
  background-color: #e9d5ff; /* 紫色背景 */
  color: #5b21b6; /* 深紫色文字 */
}

/* 主容器 */
.main-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 1.5rem;
}

/* 筛选区域 */
.filter-section {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    padding: 1.5rem;
    margin-bottom: 1.5rem;
}

.filter-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 1rem;
    margin-bottom: 1rem;
}

.search-container,
.select-container {
    position: relative;
}

.search-icon,
.select-icon,
.calendar-icon {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    width: 16px;
    height: 16px;
    color: #9ca3af;
    pointer-events: none;
}
.filter-select {
    appearance: none;
    -webkit-appearance: none;
    -moz-appearance: none;
}

.search-input,
.filter-select {
    width: 100%;
    padding: 0.5rem 0.5rem 0.5rem 2.5rem;
    border: 1px solid #d1d5db;
    border-radius: 6px;
    font-size: 0.875rem;
    background-color: white;
}

.search-input:focus,
.filter-select:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.export-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    padding: 0.5rem 1rem;
    background-color: #10b981;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 0.875rem;
    cursor: pointer;
    transition: background-color 0.2s;
}

.export-btn:hover {
    background-color: #059669;
}

.btn-icon {
    width: 16px;
    height: 16px;
}

.date-filter {
    display: flex;
    align-items: center;
    gap: 1rem;
    flex-wrap: wrap;
    position: relative;
    padding-left: 30px;
}

.date-filter .calendar-icon {
    left: 0;
}

.date-label {
    font-size: 0.875rem;
    color: #6b7280;
}

.date-input {
    padding: 0.25rem 0.75rem;
    border: 1px solid #d1d5db;
    border-radius: 4px;
    font-size: 0.875rem;
}

.date-input:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.date-separator {
    font-size: 0.875rem;
    color: #6b7280;
}

.clear-btn {
    padding: 0.25rem 0.75rem;
    background-color: #f3f4f6;
    color: #6b7280;
    border: 1px solid #d1d5db;
    border-radius: 4px;
    font-size: 0.75rem;
    cursor: pointer;
    transition: background-color 0.2s;
}

.clear-btn:hover {
    background-color: #e5e7eb;
}

/* 统计卡片 */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1rem;
    margin-bottom: 1.5rem;
}

.stat-card {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    padding: 1.5rem;
    transition: transform 0.2s, box-shadow 0.2s;
}

.stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.stat-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.stat-info {
    flex: 1;
}

.stat-label {
    font-size: 0.875rem;
    color: #6b7280;
    margin: 0 0 0.5rem 0;
}

.stat-value {
    font-size: 1.875rem;
    font-weight: 700;
    color: #111827;
    margin: 0;
}

.stat-value-green {
    color: #10b981;
}

.stat-value-blue {
    color: #3b82f6;
}

.stat-value-red {
    color: #ef4444;
}

.stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.stat-icon svg {
    width: 24px;
    height: 24px;
    color: white;
}

.stat-icon-blue {
    background-color: #3b82f6;
}

.stat-icon-green {
    background-color: #10b981;
}

.stat-icon-red {
    background-color: #ef4444;
}

.stat-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background-color: white;
}

/* 表格容器 */
.table-container {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.table-wrapper {
    overflow-x: auto;
}

.log-table {
    width: 100%;
    border-collapse: collapse;
}

.table-header {
    background-color: #f9fafb;
}

.table-th {
    padding: 0.75rem 1rem;
    text-align: left;
    font-weight: 600;
    color: #374151;
    font-size: 0.875rem;
    border-bottom: 1px solid #e5e7eb;
    white-space: nowrap;
}

.table-body {
    background-color: white;
}

.table-row {
    border-bottom: 1px solid #f3f4f6;
    transition: background-color 0.2s;
}

.table-row:last-child {
    border-bottom: none;
}

.table-row:hover {
    background-color: #f9fafb;
}
.table-td {
    padding: 0.75rem 1rem;
    font-size: 0.875rem;
    color: #374151;
    vertical-align: middle;
}
.user-name {
    font-weight: 500;
    color: #111827;
}

.operation-badge {
    padding: 0.25rem 0.75rem;
    border-radius: 12px;
    font-size: 0.75rem;
    font-weight: 500;
    text-align: center;
    display: inline-block;
}

.operation-badge-create {
    background-color: #dcfdf7;
    color: #065f46;
}

.operation-badge-update {
    background-color: #dbeafe;
    color: #1e40af;
}

.operation-badge-delete {
    background-color: #fee2e2;
    color: #991b1b;
}

.operation-badge-default {
    background-color: #f3f4f6;
    color: #374151;
}

.target-text {
    max-width: 250px;
    word-wrap: break-word;
    line-height: 1.4;
}

.status-container {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.status-icon {
    width: 8px;
    height: 8px;
    border-radius: 50%;
}

.status-icon-success {
    background-color: #10b981;
}

.status-icon-failed {
    background-color: #ef4444;
}

.status-text {
    font-size: 0.875rem;
}

.status-text-success {
    color: #065f46;
}

.status-text-failed {
    color: #991b1b;
}

/* 分页样式 */
.pagination-container {
    padding: 1rem 1.5rem;
    border-top: 1px solid #e5e7eb;
}

.pagination-mobile {
    display: flex;
    justify-content: space-between;
    gap: 1rem;
}

.pagination-desktop {
    display: none;
    justify-content: space-between;
    align-items: center;
}

.pagination-info {
    flex: 1;
}

.pagination-text {
    font-size: 0.875rem;
    color: #6b7280;
    margin: 0;
}

.font-medium {
    font-weight: 500;
}

.pagination-nav {
    display: flex;
    align-items: center;
    gap: 0.25rem;
}

.pagination-btn {
    padding: 0.5rem 1rem;
    background-color: white;
    color: #374151;
    border: 1px solid #d1d5db;
    border-radius: 4px;
    font-size: 0.875rem;
    cursor: pointer;
    transition: all 0.2s;
}

.pagination-btn:hover:not(:disabled) {
    background-color: #f9fafb;
}

.pagination-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.pagination-btn-desktop {
    padding: 0.5rem 0.75rem;
    background-color: white;
    color: #374151;
    border: 1px solid #d1d5db;
    font-size: 0.875rem;
    cursor: pointer;
    transition: all 0.2s;
}

.pagination-btn-left {
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
}

.pagination-btn-right {
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
}

.pagination-btn-normal {
    background-color: white;
    color: #374151;
}

.pagination-btn-normal:hover {
    background-color: #f9fafb;
}

.pagination-btn-active {
    background-color: #3b82f6;
    color: white;
    border-color: #3b82f6;
}

/* 响应式设计 */
@media (min-width: 768px) {
    .pagination-mobile {
        display: none;
    }
    .pagination-desktop {
        display: flex;
    }
}

@media (max-width: 768px) {
    .main-container {
        padding: 1rem;
    }
    .filter-grid {
        grid-template-columns: 1fr;
    }
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    .table-wrapper {
        font-size: 0.8rem;
    }
    .target-text {
        max-width: 150px;
    }
}

@media (max-width: 480px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
    .date-filter {
        flex-direction: column;
        align-items: flex-start;
        gap: 0.5rem;
        padding-left: 0;
    }
    .date-filter .calendar-icon {
        display: none;
    }
}
</style>
